package com.mysteel.monitor.core.command;


import com.sun.management.HotSpotDiagnosticMXBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.text.SimpleDateFormat;
import java.util.Date;


/**
 *  dump 命令
 */
public class HeapDumpCommand  {
    private static final Logger logger = LoggerFactory.getLogger(HeapDumpCommand.class);
    private String file;
    private boolean live;
    public void setFile(String file) {
        this.file = file;
    }


    public void setLive(boolean live) {
        this.live = live;
    }


    public void process() {
        int status = 0;
        try {
            String dumpFile = file;
            if (dumpFile == null || dumpFile.isEmpty()) {
                String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm").format(new Date());
                File file = File.createTempFile("heapdump" + date + (live ? "-live" : ""), ".hprof");
                dumpFile = file.getAbsolutePath();
                file.delete();
            }

//         process.write("Dumping heap to " + dumpFile + "...\n");

              run(dumpFile, live);

//            process.write("Heap dump file created\n");

        } catch (Throwable t) {
            logger.error("heap dump error", t);
//            process.write("Heap dump error: " + t.getMessage() + '\n');
            status = 1;
        } finally {
//            process.end(status);
        }

    }

    private static void run( String file, boolean live) throws IOException {
        HotSpotDiagnosticMXBean hotSpotDiagnosticMXBean = ManagementFactory
                        .getPlatformMXBean(HotSpotDiagnosticMXBean.class);
        hotSpotDiagnosticMXBean.dumpHeap(file, live);
    }

}
